const vscode = require("vscode");
const util = require("../util.js");
// const handle = require("./handle.js");
let nodeID = null;
class daodanInterface {
  constructor() {
    this._onDidChange = new vscode.EventEmitter();
    this.onDidChangeTreeData = this._onDidChange.event;
    this.apiList = [];
    this.userid = null;
    this.ctx = null;
    this.handle = null;
    this.itemID = null;

  }
  getTreeItem(ele) {
    return ele;
  }

  setctx(ct) {
    this.ctx = ct;
    // this.handle = new handle.itemHandle();
    // this.handle.setctx(ct);
    this._getLocalData();
    this.init();

  }
  init() {
    const itemTreeView = vscode.window.createTreeView("daodan.interface", {
      treeDataProvider: this,
    });
    itemTreeView.onDidChangeSelection(this.handle_node);
    this.ctx.subscriptions.push(itemTreeView);
    let that = this;
    let addcase = vscode.commands.registerCommand(
      "daodan.addCase",
      function () {
        that.addcase();
      }
    );
    this.ctx.subscriptions.push(addcase);

    let addInterface = vscode.commands.registerCommand(
      "daodan.addInterface",
      function () {
        that.addInterface();
      }
    );
    this.ctx.subscriptions.push(addInterface);
    let refresh = vscode.commands.registerCommand(
      "daodan.refreshInterface",
      function () {
        that.refresh();
      }
    );
    this.ctx.subscriptions.push(refresh);
  }
  _getLocalData() {
    const selectItem = this.ctx.globalState.get("daodan.selectItem");
    if (selectItem) {
      this.itemID = selectItem;
    } else {
      this.itemID = null;
    }
    const itm = this.ctx.globalState.get("daodan.apiList");
    if (itm) {
      const apiList = JSON.parse(itm);
      this.apiList = [...apiList];
      // console.log("本地获取：", this.itemList);
      // console.log("所有：", this.ctx.globalState.keys());
    }
    // this.refresh(this.itemID)
  }

  addcase() {
    console.log("添加项目");
    const it = {
      id: util.getID("item"),
      name: "项目名称",
      type: "file",
      interf: nodeID,
    };
    let that = this;
    vscode.window
      .showInputBox({
        prompt: "请输入新建的项目名称",
        placeHolder: "名称尽量不要重复",
      })
      .then((name) => {
        if (!name || name.trim().length == 0) {
          vscode.window.showErrorMessage("名称不能为空～");
          return;
        }
        it.name = name.trim();
        that.ctx.globalState.update(it.id, JSON.stringify(it));
      })
      .then(() => {
        if (nodeID) {
          let da = that.ctx.globalState.get(nodeID);
          if (!da) {
            vscode.window.showErrorMessage("项目参数异常～");
            return;
          }
          let itemdata = JSON.parse(da);
          if (itemdata && itemdata.type == "dir") {
            itemdata.children.push(it.id);
            that.ctx.globalState.update(itemdata.id, JSON.stringify(itemdata));
            that.refresh();
            return;
          }
        }
        that.apiList.push(it.id);

        that.ctx.globalState.update(
          "daodan.apiList",
          JSON.stringify(that.apiList)
        );
        that.refresh();
      });
  }
  addInterface() {
    console.log("添加接口");
    if (!this.itemID) {
      vscode.window.showErrorMessage("先选择项目！");
      return
    }
    const itemID=this.itemID
    const it = {
      id: util.getID("api"),
      name: "接口",
      type: "api",
      children: [],
      itemid: this.itemID,
      apiInfo:{
        path:'',
        method:'GET',
        params:{},
        headers:{},
        contentType:'none',
        body:{},
        timeout:5000,
        remark:'',
        before:[],
        after:[]
      }
    };
    let that = this;
    vscode.window
      .showInputBox({
        prompt: "请输入新建的接口名称",
        placeHolder: "名称不要重复",
      })
      .then((name) => {
        let item=that.ctx.globalState.get(itemID)
        if(!item){
          vscode.window.showErrorMessage("先选择项目~");
          return
        }
        item=JSON.parse(item)

        if (!name || name.trim().length == 0) {
          vscode.window.showErrorMessage("名称不能为空～");
          return;
        }
        it.name = name.trim();
        // 添加前后置
        it.before = [...item.before]
        const before_id = util.getID('before');
        that.ctx.globalState.update(before_id, JSON.stringify({ 'position':'before','status': false, 'id': before_id, 'content': '//请使用 js 语法\n', 'it': item.id,'aid':it.id, 'name': '',time:0 }));
        it.before.push({status:true,id:before_id})
        it.after = [...item.after]
        const after_id = util.getID('after');
        that.ctx.globalState.update(after_id, JSON.stringify({ 'position':'after','status': false, 'id': after_id, 'content': '//请使用 js 语法\n', 'it': item.id,'aid':it.id, 'name': '',time:0 }));
        it.after.push({status:true,id:after_id})
        // 以上是添加前后置
        that.ctx.globalState.update(it.id, JSON.stringify(it));
      })
      .then(() => {
        // if (nodeID) {
        //   let da = that.ctx.globalState.get(nodeID);
        //   if (!da) {
        //     vscode.window.showErrorMessage("项目参数异常～");
        //     return;
        //   }
        //   let itemdata = JSON.parse(da);
        //   if (itemdata && itemdata.type == "api") {
        //     itemdata.children.push(it.id);

        //     that.ctx.globalState.update(itemdata.id, JSON.stringify(itemdata));
        //     that.refresh();
        //     return;
        //   }
        // }
        that.apiList.push(it.id);

        that.ctx.globalState.update(
          "daodan.apiList",
          JSON.stringify(that.apiList)
        );
        that.refresh();
      });
  }
  handle_node(event) {
    let se = event.selection;
    if (se && se.length > 0) {
      nodeID = se[0].id;
    } else {
      nodeID = null;
    }
  }
  getChildren(ele) {
    if (ele) {
      // console.log("ineer", ele, ele.id);
      let itemData = this.ctx.globalState.get(ele.id);
      if (!itemData) {
        console.log(ele.id + ",子项目不存在");
        return;
      }
      let da = JSON.parse(itemData);
      if (da && da.children && da.children.length > 0) {
        return this.getItemTree(da.children);
      }
      return [];
    } else {
      // console.log("getroot");
      return this.getItemTree(this.apiList);
    }
  }
  refresh(itemID,userid) {
    if(itemID){
      this.itemID = itemID;
      
    }
    if (itemID == 0) {
      this.itemID = null;
    }
    if (userid) {
      this.userid = userid;
    }
    if (userid == 0) {
      this.userid = null;
    }
    this._getLocalData();
    this._onDidChange.fire();
  }

  getItemTree(vals) {
    let tmp = [];
    for (let index in vals) {
      let itemData = this.ctx.globalState.get(vals[index]);
      if (!itemData) {
        console.log(vals[index] + ",项目不存在");
        continue;
      }
      itemData = JSON.parse(itemData);
      if (
        !itemData.itemid ||
        itemData.itemid.length == 0 ||
        itemData.itemid !== this.itemID
      ) {
        continue;
      }
      let icon = vscode.TreeItemCollapsibleState.None;
      if (itemData.type == "api") {
        icon = vscode.TreeItemCollapsibleState.Collapsed;
      }
      tmp.push(new interfaceTree(itemData.name, icon, itemData.id,this.itemID));
    }
    return tmp;
  }
}

class interfaceTree extends vscode.TreeItem {
  constructor(label, collapsible, id,tid) {
    super(label, collapsible);
    this.tooltip = label;
    this.id = id;
    this.tid=tid;
    if (collapsible == vscode.TreeItemCollapsibleState.None) {
      this.iconPath = new vscode.ThemeIcon("watch-view-icon");
      this.contextValue = "case";
    } else {
      // this.iconPath = new vscode.ThemeIcon("notebook-mimetype");
      this.contextValue = "interface";
    }
    this.command = {
      title: "打开页面",
      command: "daodan.openWeb",
      arguments: [{
        id: id,
        tid:tid,
        aid:id,
        label: label,
        title: "接口详情",
        type: 'api',
      }],
    };
  }
}

module.exports = {
  daodanInterface,
};
